import cv2
import enum
from PySide6 import QtCore
from PySide6.QtCore import Qt
from PySide6.QtWidgets import (QDialog, QGroupBox, QPushButton, QHBoxLayout, QTextEdit, 
                             QVBoxLayout, QGridLayout)
from PySide6.QtGui import QIcon, QImage, QPixmap
from qfluentwidgets import  CaptionLabel, PushButton
import setting as c
from core.util import dumpini_shotrect
from gui.common_gui import GUI_CARD
from core.log import logger

class MOVE_DIR(enum.Enum):
    UP = enum.auto()
    DOWN = enum.auto()
    LEFT = enum.auto()
    RIGHT = enum.auto()


class SFormDevelopMode(QDialog):

    def __init__(self, father, title, card, ini_idx):
        super().__init__()
        self.title = title
        self.card = card
        self.ini_idx = ini_idx
        
        self.father = father
        
        self.img_path = None
        self.img_rect = []
        self.img_height = 0
        self.img_width = 0
        
        self.setWindowIcon(QIcon(c.icon_dir_path))
        self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        
        self.initUI()
        self.ok = False
        
     # 绘制界面
    def initUI(self):
        
        self.CreateWindowCommbo()
        
        gridLayout = QGridLayout() 
        gridLayout.addWidget(self.vWinGroupBox, 0, 0, QtCore.Qt.AlignLeft)
        
        # 调用方法绘制界面
        self.setWindowTitle(c.WINTITLE)
        mainLayout = QHBoxLayout()
        mainLayout.addLayout(gridLayout)
        self.setLayout(mainLayout)
        
    def CreateWindowCommbo(self):
        
        self.image_label = CaptionLabel()
        
        layout_outter = QVBoxLayout()
                
        self.vWinGroupBox = QGroupBox(f"{self.title}")
    
        layout = QVBoxLayout()
        layout.addWidget(self.image_label)
        layout_outter.addLayout(layout)
        
        self.top_left_lb = CaptionLabel()
        self.top_left_lb.setText("左上角：")
        self.top_left_up_btn = PushButton('↑')
        self.top_left_up_btn.clicked.connect(lambda: self.onclick_move(0, MOVE_DIR.UP))
        self.top_left_down_btn = PushButton('↓')
        self.top_left_down_btn.clicked.connect(lambda: self.onclick_move(0, MOVE_DIR.DOWN))
        self.top_left_left_btn = PushButton('←')
        self.top_left_left_btn.clicked.connect(lambda: self.onclick_move(0, MOVE_DIR.LEFT))
        self.top_left_right_btn = PushButton('→')
        self.top_left_right_btn.clicked.connect(lambda: self.onclick_move(0, MOVE_DIR.RIGHT))
        
        layout = QHBoxLayout()
        layout.addWidget(self.top_left_lb)
        layout.addWidget(self.top_left_up_btn)
        layout.addWidget(self.top_left_down_btn)
        layout.addWidget(self.top_left_left_btn)
        layout.addWidget(self.top_left_right_btn)
        
        layout_outter.addLayout(layout)
        
        self.bottom_right_lb = CaptionLabel()
        self.bottom_right_lb.setText("右下角：")
        self.bottom_right_up_btn = PushButton('↑')
        self.bottom_right_up_btn.clicked.connect(lambda: self.onclick_move(1, MOVE_DIR.UP))
        self.bottom_right_down_btn = PushButton('↓')
        self.bottom_right_down_btn.clicked.connect(lambda: self.onclick_move(1, MOVE_DIR.DOWN))
        self.bottom_right_left_btn = PushButton('←')
        self.bottom_right_left_btn.clicked.connect(lambda: self.onclick_move(1, MOVE_DIR.LEFT))
        self.bottom_right_right_btn = PushButton('→')
        self.bottom_right_right_btn.clicked.connect(lambda: self.onclick_move(1, MOVE_DIR.RIGHT))
        
        layout = QHBoxLayout()
        layout.addWidget(self.bottom_right_lb)
        layout.addWidget(self.bottom_right_up_btn)
        layout.addWidget(self.bottom_right_down_btn)
        layout.addWidget(self.bottom_right_left_btn)
        layout.addWidget(self.bottom_right_right_btn)
        layout_outter.addLayout(layout)
        
        
        self.reset_btn = PushButton('重置')
        self.reset_btn.clicked.connect(lambda: self.onclick_reset(self.card, self.ini_idx))
        self.ok_btn = PushButton('保存')
        self.ok_btn.clicked.connect(lambda: self.onclick_ok(self.card, self.ini_idx))
        layout = QHBoxLayout()
        layout.addWidget(self.reset_btn)
        layout.addWidget(self.ok_btn)
        layout_outter.addLayout(layout)
        
        layout = QHBoxLayout()
        self.tips_label = CaptionLabel('')
        layout.addWidget(self.tips_label)
        layout_outter.addLayout(layout)
        
        
        self.vWinGroupBox.setLayout(layout_outter)
    
    def UpdateImage(self, img_path, rect):
        
        self.img_path = img_path
        cv_image = cv2.imread(img_path)
        # 将图像转换为 RGB 格式
        cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
        
        height, width, channel = cv_image.shape
        self.img_height = height
        self.img_width = width
        # logger.info(f"cv2 {height} {width} {factor_x} {facotr_y}")
        # print(f"Height: {height} Width {width}")
        bytesPerLine = 3 * width
        
        
        
        if rect[0] > width:
            rect[0] = 0
        if rect[2] > width:
            rect[2] = width
        if rect[1] > height:
            rect[1] = 0
        if rect[3] > height:
            rect[3] = height
        
        self.img_rect = rect
        logger.info(f"rect {rect}")
        
        top_left = (rect[0], rect[1])
        bottom_right  = (rect[2], rect[3])
        
        cv2.rectangle(cv_image, top_left, bottom_right, (255, 0, 0), 5)
        
        # 将 OpenCV 图像转换为 QImage
        qImage = QImage(cv_image.data, width, height, bytesPerLine, QImage.Format_RGB888)
        
        # 从 QImage 创建 QPixmap
        pixmap = QPixmap.fromImage(qImage)
        
        # pixmap = QPixmap(map_img_path)  
        scaled_pixmap = pixmap.scaled(c.win_width-80, c.win_width-80, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        width = scaled_pixmap.width()
        height = scaled_pixmap.height()
        # logger.info(f"w: {width}, h: {height}")
        self.image_label.setPixmap(scaled_pixmap)
        
    def SetTitle(self, title):
        self.title = title
        self.vWinGroupBox.setTitle(title)
    
    def SetIndex(self, index):
        self.ini_idx = index
        
    def onclick_move(self, point, dir):
        self.setTips("")
        print(f"{point} {dir} ")
        step = 10
        
        idx_x = 0
        range_x = []
        idx_y = 0
        range_y = []
        if point == 0:
            idx_x = 0
            range_x = [step, self.img_rect[2]-step]
            idx_y = 1
            range_y = [step, self.img_rect[3]-step]
            
        else:
            idx_x = 2
            range_x = [self.img_rect[0]+step, self.img_width-step]
            idx_y = 3
            range_y = [self.img_rect[1]+step, self.img_height-step]
            
        
        if dir == MOVE_DIR.UP :
            if self.img_rect[idx_y] > range_y[0]:
                self.img_rect[idx_y] -= step
            else:
                self.img_rect[idx_y] = range_y[0] - step
        elif dir == MOVE_DIR.DOWN :
            if self.img_rect[idx_y] < range_y[1]:
                self.img_rect[idx_y] += step
            else:
                self.img_rect[idx_y] = range_y[1] + step
        elif dir == MOVE_DIR.LEFT :
            if self.img_rect[idx_x] > range_x[0]:
                self.img_rect[idx_x] -= step
            else:
                self.img_rect[idx_x] = range_x[0] - step
        elif dir == MOVE_DIR.RIGHT :
            if self.img_rect[idx_x] < range_x[1]:
                self.img_rect[idx_x] += step
            else:
                self.img_rect[idx_x] = range_x[1] + step
        else:
            print(f"Invalid dir: {dir}")
            return
            
        self.UpdateImage(self.img_path, self.img_rect)
        
    def onclick_ok(self, card, ini_idx):
        print(f"save {card} {ini_idx} ")
        if card == GUI_CARD.COORD:
            c.coord_shot_rect = self.img_rect
        elif card == GUI_CARD.QA:
            c.qa_shot_rect[ini_idx] = self.img_rect
        else:
            print(f"Invalid card : {card}")
            self.setTips(f"保存失败：非法 {card}")
            return
        dumpini_shotrect(c.qa_shot_rect, c.coord_shot_rect)
        self.setTips("保存成功")
        
    def onclick_reset(self, card, ini_idx):
        print(f"reset {card} {ini_idx} ")
        if card == GUI_CARD.COORD:
            self.img_rect = c.coord_shot_rect_default.copy()
            print(f"{self.img_rect}")
            c.coord_shot_rect = self.img_rect.copy()
        elif card == GUI_CARD.QA:
            self.img_rect = c.qa_shot_rect_default[ini_idx].copy()
            c.qa_shot_rect[ini_idx] = self.img_rect.copy()
        else:
            print(f"Invalid card : {card}")
            self.setTips(f"保存失败：非法 {card}")
            return
        dumpini_shotrect(c.qa_shot_rect, c.coord_shot_rect)
        self.setTips("重置成功")
        self.UpdateImage(self.img_path, self.img_rect)
        
    def setTips(self, tips):
        self.tips_label.setText(f"<font color='red'>{tips}</font>")
    
    